package com.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.proj.Info;
import com.proj.InfoDao;
import com.proj.InfoInterface;
import com.proj.Tag;

import java.util.Arrays;
import java.util.Collection;

import static com.controller.Utility.*;

public class InfoController {
    InfoInterface infoInterface;

    public String handle(String payload) {
        String op = (String) JSON.parseObject(payload).get("type");
        String response;

        switch (op) {
            case "req_updateInfo": {
                response = parsePayloadToClassThen(payload, jTag.class, t -> {
                    infoInterface.updateInfo(new InfoDao(t.id, t.name, t.details));
                    return "ok";
                });
                break;
            }
            case "req_addInfo": {
                response = parsePayloadToClassThen(payload, jInfo.class, t -> {
                    Info info = infoInterface.createInfo(t.name, t.content);
                    return JSON.toJSONString(new jResultCrate<>("resp_addInfo", info.getId()));
                });
                break;
            }
            case "req_deleteInfo": {
                response = parsePayloadToStringThenUpdate(payload, infoInterface::deleteInfo);
                break;
            }
            case "req_addTagForInfo": {
                response = parsePayloadToClassThen(payload, JSONObject.class, t -> {
                    infoInterface.addTagForInfo(t.getString("tagId"), t.getString("infoId"));
                    return "ok";
                });
                break;
            }
            case "req_getTagsByInfo": {
                response = parsePayloadToStringThenQuery(payload, infoId -> {
                    Collection<Tag> tags = infoInterface.getTagsOnInfo(infoId);
                    return JSON.toJSONString(new jResultCrate<>("resp_getTagsByInfo", tags));
                });
                break;
            }
            case "req_getInfoById": {
                response = parsePayloadToClassThen(payload, String[].class, (String[] ids) -> {
                    Collection<Info> infos = infoInterface.getInfoById(Arrays.asList(ids));
                    return JSON.toJSONString(new jResultCrate<>("resp_getInfoById", infos));
                });
                break;
            }
            case "req_getInfoByName": {
                response = parsePayloadToStringThenQuery(payload, infoName -> {
                    Info info = infoInterface.getInfoByName(infoName);
                    return JSON.toJSONString(new jResultCrate<>("resp_getInfoByName", info));
                });
                break;
            }
            default: {
                response = errBadRequest();
                break;
            }
        }

        return response;
    }

}
